package com.xf.common.core.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.xf.common.core.constant.CommonConstants;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Profile;
import springfox.bean.validators.configuration.BeanValidatorPluginsConfiguration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @Description
 * @Author FengYi
 * @Date 2020-06-05 9:17
 */
@Configuration
@EnableKnife4j
@EnableSwagger2
@Profile({"dev", "test"})
@Import(BeanValidatorPluginsConfiguration.class)
public class SwaggerAutoConfiguration {

    @Value("${spring.application.name}")
    private String applicationName = "APP_NAME";

    @Bean
    public Docket createRestApi() {
        // 添加请求参数，我们这里把token作为请求头部参数传入后端

        List<Parameter> parameters = new ArrayList<Parameter>();

        Parameter token = new ParameterBuilder().name(CommonConstants.Authorization).description(CommonConstants.Authorization)
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build();

        Parameter organizationId = new ParameterBuilder().name(CommonConstants.ORGANIZATION_ID).description("组织id")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build();

        Parameter signupApplication = new ParameterBuilder().name(CommonConstants.SIGNUPAPPLICATION).description("登录的app")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build();

        parameters.addAll(Arrays.asList(token, organizationId, signupApplication));
        return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
                .select()
                .apis(basePackages(Arrays.asList("com.xf")))
                .paths(PathSelectors.any())
                .paths(Predicates.not(PathSelectors.regex("/error.*")))// 错误路径不监控
                .build().globalOperationParameters(parameters);
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("DMP 中小企业版接口文档")
                .description("This is a restful api document of DMP Project.")
                .contact(new Contact("Ren Xiao Man", "", "762879434@qq.com"))
                .version("1.0")
                .termsOfServiceUrl("/" + applicationName)
                .build();
    }

    public static Predicate<RequestHandler> basePackages(final List<String> basePackages) {
        return input -> declaringClass(input).transform(handlerPackage(basePackages)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final List<String> basePackages) {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackages) {
                Api api = input.getAnnotation(Api.class);
                boolean isMatch = input.getPackage().getName().startsWith(strPackage) && Objects.nonNull(api) /*&& input.getPackage().getName().contains("controller")*/;
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }
}
